
//
//  ViewController.m
//  TestWebview
//
//  Created by 谭谭伟 on 17/3/8.
//  Copyright © 2017年 谭谭伟. All rights reserved.
//

#import "MNDMainViewController.h"
#import "UserDefaultsTool.h"
#import <AFNetworking.h>
#import <Masonry.h>
#import "UIColor+HMAddition.h"
#import <SVProgressHUD.h>
#import "MNDGestureViewController.h"
#import "UIColor+HMAddition.h"
#import "MNDSetGestureTableViewController.h"
#import <JHUD.h>
#import "MNDLinkerViewController.h"

//判断系统版本
#define iOS10 ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0)
//网络请求地址
#define RequestAdress @"http://m.miniwangdai.com/mobile/#/home/0"

//论坛
#define ForumSafriAdress @"http://bbs.miniwangdai.com/"
//注册
#define RegistSafriAdress @"http://www.miniwangdai.com/public/xieyi.html"
//注册
#define RegistSafriAdress2 @"https://www.miniwangdai.com/public/xieyi.html"
//授权协议
#define AuthorizeSafriAdress @"http://miniwangdai.com/public/xieyi2.html"
//江西银行协议
#define BankAuthorizeSafriAdress @"http://miniwangdai.com/public/xieyi1.html"
//债权转让协议
#define CreditorAuthorizeSafriAdress @"http://miniwangdai.com/public/pact/creditor_transfer.html"
//清除缓存
#define CleanCache @"app://clearCache"
//注册抢卷协议
#define RegistAuthorizeSafriAdress @"https://miniwangdai.com/public/xieyi.html"
//安全退出
#define SafeExit @"http://m.miniwangdai.com/mobile/#/home"
//跳转设置手势
#define SetGesture @"http://www.baidu.com/"
//账户安全
#define AccountSafe @"https://miniwangdai.com/mobile/#/zhanghu_safe"
@interface MNDMainViewController ()

/* 数据加载遮盖图片 */
@property (strong, nonatomic) UIImageView *imgView;

@end

@implementation MNDMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"";
    self.webview.scrollView.bounces = NO;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //如果用户没有退出，进入时需要输入手势
    NSString *psswordDocuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *passwordFilePath = [psswordDocuPath stringByAppendingPathComponent:@"password"];
    NSString *password = [NSKeyedUnarchiver unarchiveObjectWithFile:passwordFilePath];
    
    if (password != nil) {
        [self gotoGestureVC];
    }
    
    //nav返回按钮颜色
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    //nav背景颜色
    [[UINavigationBar appearance] setBarTintColor:[UIColor hm_colorWithHex:0xff6300]];

    //注册通知
    [self registNotification];
}



- (void)viewWillAppear:(BOOL)animated {
    
//    self.navigationController.navigationBar.translucent = YES;//透明
//    [self setStatusBarBackgroundColor:[UIColor clearColor]];
    
  
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;

//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
//    [self observeNetworkState];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark -搭建新特性页面
- (void)setupNewFeatureView {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *versionKey = @"CFBundleShortVersionString";
        //取到上一次版本号
        NSString *previousVersion = [UserDefaultsTool objetForKey:versionKey];
        //取到当前版本号
        NSString *currentVersion = [NSBundle mainBundle].infoDictionary[versionKey];
        
        UIImageView *imgview = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _imgView = imgview;

        _imgView.image = [UIImage imageNamed:@"KeepImage"];
        [self.view addSubview:_imgView];

        
        //比较版本是否一致
        if ([currentVersion isEqualToString:previousVersion]) {
            
            [_featureView removeFromSuperview];
//            [JHUD showAtView:self.view message:@"努力加载中..."];
            
            
        } else {
            _featureView = [[MNDNewFeatureView alloc]initWithFrame:self.view.bounds];
            
            _featureView.featurePictureArray = @[@"启动页-1",@"启动页-2",@"启动页-3",@"启动页-4"];
            [self.view addSubview:_featureView];
            //设置错误的次数
            NSString *erroCount = @"5";
            [UserDefaultsTool saveObject:erroCount forKey:@"erroCount"];
            //保存版本号
            [UserDefaultsTool saveObject:currentVersion forKey:versionKey];
            
        }
    });
    
}

#pragma mark -监听网络
- (void)observeNetworkState {
    
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    //设置无网络图片
    UIView *placeHolderView = [[UIView alloc]initWithFrame:self.view.bounds];
    
    placeHolderView.backgroundColor = [UIColor hm_colorWithHex:0xf3f4f6];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 0) {//无网络
            //去除菊花
            [SVProgressHUD dismiss];
            
            [self showSettingNetwork];
            
            //记录网络状态
            self.networkStatus = NO;
    
            
        }else {

        }
    }];
    //开始监听
    [reachabilityManager startMonitoring];
}



#pragma mark -点击重新加载数据
- (void)clickReloadData {
    if (self.networkStatus ) {
        [self loadWebviewData];
        
    }else {
        [self showSettingNetwork];
        
    }
    
}

#pragma mark -如果没网，去设置网络

- (void)showSettingNetwork {
    //创建无网络提示label
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"蜂窝移动数据已关闭" message:@"打开蜂窝移动数据或使用Wi-Fi来访问" preferredStyle:UIAlertControllerStyleAlert];
    //去系统设置网络
    UIAlertAction *setNetworkAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self setNetWork];
    }];
    //取消设置
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    //添加到控制器
    [alertController addAction:setNetworkAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

//设置网络
- (void)setNetWork {
    NSString * urlString = @"App-Prefs:root=MOBILE_DATA_SETTINGS_ID";
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
        if (iOS10) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }
    }
}

#pragma mark -加载数据

- (void)loadWebviewData {
    
    NSString *versionKey = @"CFBundleShortVersionString";
    //取到上一次版本号
    NSString *previousVersion = [UserDefaultsTool objetForKey:versionKey];
    //取到当前版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[versionKey];
    
    if ([currentVersion isEqualToString:previousVersion] == NO) {
    
        self.featureVersion = YES;
        //设置手势开关的初始值
        [UserDefaultsTool saveBool:YES forKey:@"gestureSwitch"];
        
    }else {
        self.featureVersion = NO;
    }
    
    NSURL *webUrl = [NSURL URLWithString:RequestAdress];
        //        NSURLRequest *webRequest = [NSURLRequest requestWithURL:webUrl];
   
    UIWebView *webview = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //    self.webview = webview;
    [webview setBackgroundColor:[UIColor clearColor]];
    webview.scrollView.bounces = NO;
    
    //自动检测号码，点击可以拨打
    webview.dataDetectorTypes = YES;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         NSURLRequest *webRequest = [NSURLRequest requestWithURL:webUrl cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
        [webview loadRequest:webRequest];
    });
    
    webview.delegate = self;
    self.webview = webview;
//    self.webview.scrollView.decelerationRate = 0.1;
//    self.webview.scrollView.contentSize = CGSizeMake(0, self.view.bounds.size.height*2);
    [self.view addSubview:webview];
//    [JHUD hideForView:self.view];
    [self setupNewFeatureView];
    
}


#pragma mark -UIWebViewDelegate
-(void)webViewDidStartLoad:(UIWebView *)webView {
    
    
    
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
    
    

//    [JHUD hideForView:self.view];
//    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
//        设置放大倍数
            CGFloat scale = 3.0;
        
             [UIView animateWithDuration:0.5 animations:^{
                 //放大
                 _imgView.transform = CGAffineTransformMakeScale(scale, scale);
                 //透明
                 _imgView.alpha = 0;
            } completion:^(BOOL finished) {
                //移除
                [_imgView removeFromSuperview];
            }];
    });
    
//    [SVProgressHUD dismiss];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    
//    [self saveCookie];
    
    //请求数据时判断网络
    [self observeNetworkState];
    NSString *absoluteStr = request .URL.absoluteString;
    //判断手势是否设定
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docuPath stringByAppendingPathComponent:@"setGesture"];
    NSString *setGesture = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    //注入版本号
//    if ([absoluteStr isEqualToString:@"http://m.miniwangdai.com/mobile/#/shezhi"]) {
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [webView stringByEvaluatingJavaScriptFromString: @"banben_num('v3.0.2');"];
//        });
//    }
    
    //进入账号安全时判断手势密码的设定状态
    if ([absoluteStr isEqualToString:AccountSafe]) {//进入账号安全
        
        if (![setGesture isEqualToString:@"NO"]) {//未设置
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self withoutSetGesture];
            });

            
        } else {//已设置
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self finishSetGesture];
            });
            
        }

    }
    
    //点击手势密码，跳转的手势设置控制器
    if ([absoluteStr isEqualToString:SetGesture] ) {
        [UserDefaultsTool saveBool:NO forKey:@"confirmPassword"];
        [webView stopLoading];
//        MNDGestureViewController *gestureViewcontroller = [[MNDGestureViewController alloc]init];
//        gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
//        
//        [self.navigationController pushViewController:gestureViewcontroller animated:YES];
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"GestureStoryboard" bundle:nil];
        MNDSetGestureTableViewController *setGestureVC = [storyboard instantiateViewControllerWithIdentifier:@"SetGesture"];
        setGestureVC.view.backgroundColor = [UIColor whiteColor];
        UILabel *navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 62, 20)];
        navLabel.text = @"手势密码";
        navLabel.textColor = [UIColor whiteColor];
        setGestureVC.navigationItem.titleView = navLabel;
        [self.navigationController pushViewController:setGestureVC animated:YES];
        
                return NO;
    }
    NSLog(@"url: %@", request.URL);
    if ([absoluteStr containsString:@"miniwangdai.com/public/"] || [absoluteStr containsString:@"bbs.miniwangdai.com/"]) {
        
        MNDLinkerViewController *linkerVC = [[MNDLinkerViewController alloc] init];
        linkerVC.linkUrl = absoluteStr;
        
        [self.navigationController pushViewController:linkerVC animated:YES];
        
        return NO;
    }
//    //论坛跳转到safri
//    if ([absoluteStr isEqualToString:ForumSafriAdress] ) {
//        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:ForumSafriAdress]];
////        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:ForumSafriAdress] options:@{} completionHandler:nil];
//               return NO;
//    }
//    //注册跳转到safri
//    if ([absoluteStr isEqualToString:RegistSafriAdress]) {
//        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:RegistSafriAdress]];
////        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:RegistSafriAdress] options:@{} completionHandler:nil];
//        return NO;
//    }
//    //用户授权跳转到safri
//    if ([absoluteStr isEqualToString:AuthorizeSafriAdress]) {
//        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:AuthorizeSafriAdress]];
////         [[UIApplication sharedApplication]openURL:[NSURL URLWithString:AuthorizeSafriAdress] options:@{} completionHandler:nil];
//        return NO;
//    }
//    
//    //银行协议跳转到safri
//    if ([absoluteStr isEqualToString:BankAuthorizeSafriAdress]) {
//        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:BankAuthorizeSafriAdress]];
////        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:BankAuthorizeSafriAdress] options:@{} completionHandler:nil];
//        return NO;
//    }
//
//    //债权转让协议跳转到safri
//    if ([absoluteStr isEqualToString:CreditorAuthorizeSafriAdress]) {
//        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:CreditorAuthorizeSafriAdress]];
////        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:CreditorAuthorizeSafriAdress] options:@{} completionHandler:nil];
//        return NO;
//    }
    
    //清除缓存
    if ([absoluteStr isEqualToString:CleanCache]) {
        [self cleanCacheAndCookie];
        return NO;
    }
    //如果安全退出，清空手势密码及状态,清空缓存
    if([absoluteStr isEqualToString:SafeExit]) {
        [self cleanGesture];
//        [self cleanCacheAndCookie];

    }
    return YES;
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
//    [self showErrorInfo];
}

- (void)showErrorInfo{
    //创建无网络提示label
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请求错误" message:@"请重新加载或检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
    //去系统设置网络
    UIAlertAction *setNetworkAction = [UIAlertAction actionWithTitle:@"设置网络" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self setNetWork];
    }];
    //取消设置
    UIAlertAction *reloadAction = [UIAlertAction actionWithTitle:@"重新加载" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.webview reload];
    }];
    
    //添加到控制器
    [alertController addAction:setNetworkAction];
    [alertController addAction:reloadAction];
    [self presentViewController:alertController animated:YES completion:nil];

}

#pragma mark -注册通知
- (void)registNotification {
    //还没有设置手势
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(withoutSetGesture) name:@"WithoutSetGesture" object:nil];
    
    //设置完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishSetGesture) name:@"FinishSetGesture" object:nil];
    
    //显示手势密码验证
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoGestureVC) name:@"showGesture" object:nil];
    
    //登出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(signOut) name:@"signOut" object:nil];
    
    //菊花
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoading) name:@"showMinidaiNotification" object:nil];
}


#pragma mark -接收通知后执行

- (void)withoutSetGesture {
    NSMutableString *stringM = [NSMutableString string];
    [stringM appendString:@"pass_hand('1')"];
    [self.webview stringByEvaluatingJavaScriptFromString:stringM];
}
- (void)finishSetGesture {
    NSMutableString *stringM = [NSMutableString string];
    [stringM appendString:@"pass_hand('0')"];
    [self.webview stringByEvaluatingJavaScriptFromString:stringM];
}

- (void)gotoGestureVC {
    MNDGestureViewController *gestureViewcontroller = [[MNDGestureViewController alloc]init];
    gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
    
    //隐藏topgestureview
    gestureViewcontroller.topGestureView.hidden = YES;
    gestureViewcontroller.tipLabel.text = @"请输入手势验证";
    gestureViewcontroller.tipLabel.textColor = [UIColor blackColor];
    gestureViewcontroller.forgetPasswordBtn.hidden = NO;
    gestureViewcontroller.otherAcountLoginBtn.hidden = NO;
    gestureViewcontroller.navigationController.navigationBarHidden = YES;
    [self.navigationController pushViewController:gestureViewcontroller animated:YES];

}

//登出
- (void)signOut {
    //重置错误的次数
    NSString *erroCount = @"5";
    [UserDefaultsTool saveObject:erroCount forKey:@"erroCount"];
    
    NSMutableString *stringM = [NSMutableString string];
    [stringM appendString:@"out()"];
    [self.webview stringByEvaluatingJavaScriptFromString:stringM];
    //记录登陆状态
    [UserDefaultsTool saveBool:NO forKey:@"signIn"];
    //清空密码
    [self cleanGesture];
    [self.navigationController popViewControllerAnimated:YES];
    

}



- (void)cleanGesture {
    [UserDefaultsTool saveObject:nil forKey:@"user_code"];
    //手势改为未设置
    NSString *setGesture = @"YES";
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docuPath stringByAppendingPathComponent:@"setGesture"];
    [NSKeyedArchiver archiveRootObject:setGesture toFile:filePath];
    
    //清空手势密码
    NSString *password = nil;
    NSString *psswordDocuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *passwordFilePath = [psswordDocuPath stringByAppendingPathComponent:@"password"];
    [NSKeyedArchiver archiveRootObject:password toFile:passwordFilePath];

}


/**清除缓存和cookie*/
- (void)cleanCacheAndCookie{
    //清除cookies
    //NSHTTPCookie *cookie;
    //NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    //for (cookie in [storage cookies]){
       // [storage deleteCookie:cookie];
    //}
    
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
    [self.webview reload];
    UIImageView *imgview = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _imgView = imgview;

    _imgView.image = [UIImage imageNamed:@"KeepImage"];
    _imgView.contentMode = UIViewContentModeScaleToFill;
    [self.view addSubview:_imgView];

     [SVProgressHUD showSuccessWithStatus:@"清理缓存成功"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [_imgView removeFromSuperview];
        
        [SVProgressHUD dismiss];
   
        
    });
}


- (void)showLoading {

//    [JHUD showAtView:self.view message:@"努力加载中..."];
}


//保存cookie
- (void)saveCookie {
    NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
    for (NSHTTPCookie * cookie in cookieArr) {          //遍历cookie

        if ([cookie.name isEqualToString:@"user_code"]) {
            
                [UserDefaultsTool saveObject:cookie.properties forKey:@"user_code"];
            
        }
    }
}

//取消通知监听
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

